package portlet.dscbtt;

import java.io.IOException;

import java.sql.Timestamp;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.TimeZone;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;

import javax.faces.application.Application;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.DateTimeConverter;
import javax.faces.event.ActionEvent;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.input.RichInputDate;
import oracle.adf.view.rich.component.rich.layout.RichPanelBorderLayout;
import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;
import oracle.adf.view.rich.component.rich.nav.RichCommandLink;
import oracle.adf.view.rich.component.rich.nav.RichGoLink;
import oracle.adf.view.rich.component.rich.output.RichOutputText;
import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.jbo.Row;
import oracle.jbo.RowSet;
import oracle.jbo.domain.ClobDomain;
import oracle.jbo.domain.Number;

import oracle.portlet.bridge.adf.application.ADFBridgePortlet;
import org.apache.myfaces.trinidadinternal.taglib.util.MethodExpressionMethodBinding;

import portlet.common.Utils;
import portlet.common.search.AdvancedSearchGroup;
import portlet.common.search.AdvancedSearchItem;


public class Dscbtt extends ADFBridgePortlet {
    private RichPanelGroupLayout searchPanel=new RichPanelGroupLayout();
    private RichPanelGroupLayout danhSachPanel=new RichPanelGroupLayout();
    private RichPanelGroupLayout pagingPanel=new RichPanelGroupLayout();

    protected String getTitle(RenderRequest request) {
        // Get the customized title. This defaults to the declared title.
        PortletPreferences prefs = request.getPreferences();
        return prefs.getValue(PORTLETTITLE_KEY, super.getTitle(request));
    }
    public static final String APPLY_ACTION = "apply_action";
    public static final String OK_ACTION = "ok_action";
    public static final String PORTLETTITLE_KEY = "portletTitle";
    private static final String DEFAULT_LANGCODE = "vi";
    private final String LINK_DES = "des";
    private final String ROW_KEY = "rowkey";
    private final int DEFAULT_SIZE = 5;
    private final String SEARCH_TU_NGAY = "search_tu_ngay";
    private final String SEARCH_DEN_NGAY = "search_den_ngay";


    private String[] buildValueArray(String values) {
        if (values.indexOf(',') < 0) {
            return new String[] { values };
        }
        StringTokenizer st = new StringTokenizer(values, ",");
        String[] valueArray = new String[st.countTokens()];
        int i = 0;
        while (st.hasMoreTokens()) {
            valueArray[i] = st.nextToken().trim();
            i++;
        }
        return valueArray;
    }

    public void processAction(ActionRequest request,
                              ActionResponse response) throws PortletException,
                                                              IOException {
        request.setAttribute("javax.portlet.config", getPortletConfig());
        super.processAction(request, response);
    }

    public void render(RenderRequest request,
                       RenderResponse response) throws PortletException,
                                                       IOException {
        request.setAttribute("javax.portlet.config", getPortletConfig());
        super.render(request, response);
    }

    @Override
    protected void doView(RenderRequest renderRequest,
                          RenderResponse renderResponse) throws PortletException,
                                                                IOException {
        renderRequest.getPortletSession().setAttribute("reset", 1);
        checkParameter(renderRequest);
        super.doView(renderRequest, renderResponse);
    }

    public boolean checkParameter(RenderRequest request) {
        boolean check = true;
        String pLoaiDonViId = request.getParameter("loaidonviid");
        String pLangCode = request.getParameter("langcode");
        String pChiTietUrl = request.getParameter("chitieturl");
        String pLoaiCbttId = request.getParameter("loaicbttid");
        String pSoLuongBanGhi = request.getParameter("soluongbanghi");
        String sLoaiDonViId =
            (String)request.getPortletSession().getAttribute("loaidonviid");
        String sLangCode =
            (String)request.getPortletSession().getAttribute("langcode");
        String sChiTietUrl =
            (String)request.getPortletSession().getAttribute("chitieturl");
        String sLoaiCbttId =
            (String)request.getPortletSession().getAttribute("loaicbttid");
        String sSoLuongBanGhi =
            (String)request.getPortletSession().getAttribute("soluongbanghi");
        if (pLangCode == null) {
            pLangCode = DEFAULT_LANGCODE;
        }
        if (sLoaiDonViId != null && pLoaiDonViId != null) {
            if (sLoaiDonViId.equals(pLoaiDonViId) == false) {
                check = false;
            }
        } else if (pLoaiDonViId != null) {
            check = false;
        } else if (sLoaiDonViId != null) {
            check = false;
        }

        if (sLangCode != null && pLangCode != null) {
            if (sLangCode.equals(pLangCode) == false) {
                check = false;
            }
        } else if (pLangCode != null) {
            check = false;
        } else if (sLangCode != null) {
            check = false;
        }

        if (sChiTietUrl != null && pChiTietUrl != null) {
            if (sChiTietUrl.equals(pChiTietUrl) == false) {
                check = false;
            }
        } else if (pChiTietUrl != null) {
            check = false;
        } else if (sChiTietUrl != null) {
            check = false;
        }

        if (sLoaiCbttId != null && pLoaiCbttId != null) {
            if (sLoaiCbttId.equals(pLoaiCbttId) == false) {
                check = false;
            }
        } else if (pLoaiCbttId != null) {
            check = false;
        } else if (sLoaiCbttId != null) {
            check = false;
        }

        if (sSoLuongBanGhi != null && pSoLuongBanGhi != null) {
            if (sSoLuongBanGhi.equals(pSoLuongBanGhi) == false) {
                check = false;
            }
        } else if (pSoLuongBanGhi != null) {
            check = false;
        } else if (sSoLuongBanGhi != null) {
            check = false;
        }
        request.getPortletSession().setAttribute("loaidonviid", pLoaiDonViId);
        request.getPortletSession().setAttribute("langcode", pLangCode);
        request.getPortletSession().setAttribute("chitieturl", pChiTietUrl);
        request.getPortletSession().setAttribute("loaicbttid", pLoaiCbttId);
        request.getPortletSession().setAttribute("soluongbanghi",
                                                 pSoLuongBanGhi);
        return check;
    }

    public void changePage(ActionEvent actionEvent) {
        Integer pageNum =
            (Integer)actionEvent.getComponent().getAttributes().get("pageNum");
        if (pageNum == null) {
            pageNum = 1;
        }
        createForm(pageNum.intValue());
    }

    public String getResetForm() {
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        Integer reset =
            (Integer)request.getPortletSession().getAttribute("reset");
        if (reset != null && reset.intValue() == 1) {
            request.getPortletSession().setAttribute(SEARCH_TU_NGAY, null);
            request.getPortletSession().setAttribute(SEARCH_DEN_NGAY,null);
            resetIterator(request);
            createForm(0);
            request.getPortletSession().setAttribute("reset", 0);
            AdfFacesContext.getCurrentInstance().addPartialTarget(danhSachPanel);
        }
        return null;
    }

    private void createForm(int pageNum) {
        resetPaging("DlctCbttView1Iterator", pageNum);
        danhSachPanel.getChildren().clear();
        searchPanel.getChildren().clear();
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String chiTietUrl =
            (String)request.getPortletSession().getAttribute("chitieturl");
        String loaiDonViId =
            (String)request.getPortletSession().getAttribute("loaidonviid");
        String langCode =
            (String)request.getPortletSession().getAttribute("langcode");
        Map<String, String> mapTruongTtRoot = new HashMap();
        DCIteratorBinding truongTtView1Iterator =
            Utils.getIteratorBinding("DlctTruongTtView1Iterator");
        truongTtView1Iterator.setRangeSize(-1);
        DCIteratorBinding cbttView1Iterator =
            Utils.getIteratorBinding("DlctCbttView1Iterator");
        Row[] rows = cbttView1Iterator.getAllRowsInRange();
        if (rows == null) {
            rows = new Row[] { };
        }

        {
            SimpleDateFormat dateFormat =
                new SimpleDateFormat("yyyy/MM/dd");

            String fromSearch =
                (String)request.getPortletSession().getAttribute(SEARCH_TU_NGAY);
            String toSearch =
                (String)request.getPortletSession().getAttribute(SEARCH_DEN_NGAY);
            java.util.Date from = null;
            java.util.Date to = null;
            if (fromSearch != null) {
                try {
                    from = dateFormat.parse(fromSearch);
                } catch (ParseException e) {
                }
            }
            if (toSearch != null) {
                try {
                    to = dateFormat.parse(toSearch);
                } catch (ParseException e) {
                }
            }

            DateTimeConverter converter =
                (DateTimeConverter)FacesContext.getCurrentInstance().getApplication().createConverter("javax.faces.DateTime");
            converter.setLocale(new Locale(DEFAULT_LANGCODE));
            converter.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
            converter.setType("date");
            converter.setDateStyle("short");
            RichInputDate inputDate = new RichInputDate();
            inputDate.setConverter(converter);
            inputDate.setId(SEARCH_TU_NGAY);
            inputDate.setAutoSubmit(true);
            inputDate.setLabel(getResource("TU_NGAY"));
            inputDate.setValue(from);
            searchPanel.getChildren().add(inputDate);
            inputDate = new RichInputDate();
            inputDate.setAutoSubmit(true);
            inputDate.setConverter(converter);
            inputDate.setId(SEARCH_DEN_NGAY);
            inputDate.setLabel(getResource("DEN_NGAY"));
            inputDate.setValue(to);
            searchPanel.getChildren().add(inputDate);
            FacesContext fc = FacesContext.getCurrentInstance();
            Application app = fc.getApplication();
            ExpressionFactory elFactory =
                app.getExpressionFactory();
            ELContext elContext = fc.getELContext();
            MethodExpression methodExpression =
                elFactory.createMethodExpression(elContext,
                                                 "#{dscbtt.timKiem}",
                                                 null,
                                                 new Class[] { ActionEvent.class });
            MethodExpressionMethodBinding methodExpressionMethodBinding =
                new MethodExpressionMethodBinding(methodExpression);
            RichCommandButton buttonSearch =
                new RichCommandButton();
            buttonSearch.setId("searchbutton");
            buttonSearch.setText(getResource("TIM_KIEM"));
            buttonSearch.setPartialSubmit(true);
            buttonSearch.setInlineStyle("margin-bottom:10px;margin-top:5px;");
            buttonSearch.getAttributes().put("actionListener",
                                             methodExpressionMethodBinding);
            searchPanel.getChildren().add(buttonSearch);
        }
        for (int i = 0; i < rows.length; i++) {
            cbttView1Iterator.setCurrentRowIndexInRange(i);
            HashMap<String, Object> mapValue = new HashMap();
            String rowKey =
                cbttView1Iterator.getCurrentRow().getKey().toStringFormat(false);
            mapValue.put(ROW_KEY, rowKey);
            RowSet rowSetGtTt =
                (RowSet)cbttView1Iterator.getCurrentRow().getAttribute("DlctGtCbttTtView");
            if (rowSetGtTt != null) {
                rowSetGtTt.setRangeSize(-1);
                Row[] rowsGtTt = rowSetGtTt.getAllRowsInRange();
                if (rowsGtTt == null) {
                    rowsGtTt = new Row[] { };
                }
                for (int j = 0; j < rowsGtTt.length; j++) {
                    Row truongTtRow =
                        (Row)rowsGtTt[j].getAttribute("DlctTruongTtView");
                    if (truongTtRow != null) {
                        Number id = (Number)truongTtRow.getAttribute("Id");
                        Number kieuDuLieu =
                            (Number)truongTtRow.getAttribute("KieuDuLieu");
                        if (id != null && kieuDuLieu != null) {
                            int kieu = kieuDuLieu.intValue();
                            if (kieu ==
                                Utils.ENUM_KIEU_DU_LIEU.NUMBER.getId()) {
                                Number valNumber =
                                    (Number)rowsGtTt[j].getAttribute("ValNumber");
                                if (valNumber != null) {
                                    mapValue.put(id.toString(),
                                                 valNumber.toString());
                                }
                            }
                            if (kieu ==
                                Utils.ENUM_KIEU_DU_LIEU.VARCHAR.getId()) {
                                String valVarchar =
                                    (String)rowsGtTt[j].getAttribute("ValVarchar");
                                if (valVarchar != null) {
                                    mapValue.put(id.toString(), valVarchar);
                                }
                            }
                            if (kieu == Utils.ENUM_KIEU_DU_LIEU.LINK.getId()) {
                                String valVarchar =
                                    (String)rowsGtTt[j].getAttribute("ValVarchar");
                                if (valVarchar != null) {
                                    String link = valVarchar.toLowerCase();
                                    if (link.startsWith("http://") == false) {
                                        link = "http://" + link;
                                    }
                                    mapValue.put(id.toString() + LINK_DES,
                                                 link);
                                    mapValue.put(id.toString(), valVarchar);
                                }
                            }
                            if (kieu ==
                                Utils.ENUM_KIEU_DU_LIEU.EMAIL.getId()) {
                                String valVarchar =
                                    (String)rowsGtTt[j].getAttribute("ValVarchar");
                                if (valVarchar != null) {
                                    String link =
                                        "mailto:" + valVarchar.toLowerCase();
                                    mapValue.put(id.toString() + LINK_DES,
                                                 link);
                                    mapValue.put(id.toString(), valVarchar);
                                }
                            }
                            if (kieu == Utils.ENUM_KIEU_DU_LIEU.DATE.getId()) {
                                oracle.jbo.domain.Date valDate =
                                    (oracle.jbo.domain.Date)rowsGtTt[j].getAttribute("ValDate");
                                if (valDate != null) {
                                    java.util.Date date = valDate.dateValue();
                                    if (date != null) {
                                        mapValue.put(id.toString(), date);
                                    }
                                }
                            }
                            if (kieu == Utils.ENUM_KIEU_DU_LIEU.CLOB.getId()) {
                                ClobDomain valClob =
                                    (ClobDomain)rowsGtTt[j].getAttribute("ValClob");
                                if (valClob != null) {
                                    mapValue.put(id.toString(),
                                                 valClob.toString());
                                }
                            }
                            if (kieu == Utils.ENUM_KIEU_DU_LIEU.FILE.getId()) {
                                Row fileViewRow =
                                    (Row)rowsGtTt[j].getAttribute("HtFileView");
                                if (fileViewRow != null) {
                                    mapValue.put(id.toString(), fileViewRow);
                                }
                            }
                        }
                    }
                }
            }
            Row rowDonVi =
                (Row)cbttView1Iterator.getCurrentRow().getAttribute("DlctDonViView");
            if (rowDonVi != null) {
                RowSet gtDvTtRowSet =
                    (RowSet)rowDonVi.getAttribute("DlctGtDvTtView");
                String ten = "";
                if (gtDvTtRowSet != null) {
                    gtDvTtRowSet.setRangeSize(-1);
                    Row[] gtDvTtRows = gtDvTtRowSet.getAllRowsInRange();
                    if (gtDvTtRows == null) {
                        gtDvTtRows = new Row[] { };
                    }
                    for (int k = 0; k < gtDvTtRows.length; k++) {
                        Row gtDvTtTruongTtRow =
                            (Row)gtDvTtRows[k].getAttribute("DlctTruongTtView");
                        Number gtDvTtKieuDuLieu =
                            (Number)gtDvTtTruongTtRow.getAttribute("KieuDuLieu");
                        Number gtDvTtViTriHienThi =
                            (Number)gtDvTtTruongTtRow.getAttribute("ViTriHienThi");
                        if (gtDvTtViTriHienThi != null &&
                            gtDvTtKieuDuLieu != null) {
                            int gtLckviTri = gtDvTtViTriHienThi.intValue();
                            int gtLckKieu = gtDvTtKieuDuLieu.intValue();
                            if ((Utils.ENUM_VI_TRI_HIEN_THI.PORTLET_SELECT.getId() &
                                 gtLckviTri) ==
                                Utils.ENUM_VI_TRI_HIEN_THI.PORTLET_SELECT.getId()) {
                                if (gtLckKieu ==
                                    Utils.ENUM_KIEU_DU_LIEU.NUMBER.getId()) {
                                    Number valNumber =
                                        (Number)gtDvTtRows[k].getAttribute("ValNumber");
                                    if (valNumber != null) {
                                        ten = ten + valNumber.toString() + " ";
                                    }
                                }
                                if (gtLckKieu ==
                                    Utils.ENUM_KIEU_DU_LIEU.VARCHAR.getId()) {
                                    String valVarchar =
                                        (String)gtDvTtRows[k].getAttribute("ValVarchar");
                                    if (valVarchar != null) {
                                        ten = ten + valVarchar + " ";
                                    }
                                }
                            }
                        }
                    }
                }
                mapValue.put("donvi", ten);
            }
            List<UIComponent> listTieuDe = new ArrayList();
            List<UIComponent> listNgayThang = new ArrayList();
            Row[] rowsTruongTt = truongTtView1Iterator.getAllRowsInRange();
            if (rowsTruongTt == null) {
                rowsTruongTt = new Row[] { };
            }
            for (int j = 0; j < rowsTruongTt.length; j++) {
                String id =
                    ((Number)rowsTruongTt[j].getAttribute("Id")).toString();
                Number kieuDuLieu =
                    (Number)rowsTruongTt[j].getAttribute("KieuDuLieu");
                Number viTriHienThi =
                    (Number)rowsTruongTt[j].getAttribute("ViTriHienThi");
                Row loopRow = rowsTruongTt[j];
                Row rootRow = null;
                while (loopRow != null) {
                    rootRow = loopRow;
                    loopRow =
                            (Row)loopRow.getAttribute("DlctTruongTtTuIdDlctTruongTtView");
                }
                String rootId =
                    ((Number)rootRow.getAttribute("Id")).toString();
                if (viTriHienThi != null && kieuDuLieu != null) {
                    int viTri = viTriHienThi.intValue();
                    int kieu = kieuDuLieu.intValue();
                    mapTruongTtRoot.put(id, rootId);
                    if ((Utils.ENUM_VI_TRI_HIEN_THI.PORTLET_TIN_TIEU_DE.getId() &
                         viTri) ==
                        Utils.ENUM_VI_TRI_HIEN_THI.PORTLET_TIN_TIEU_DE.getId()) {
                        Object obj = mapValue.get(rootId);
                        if (obj != null) {
                            RichGoLink goLink = new RichGoLink();
                            goLink.setTargetFrame("_parent");
                            goLink.setText(obj.toString());
                            goLink.setDestination(chiTietUrl + "?cbttid=" +
                                                  rowKey +
                                                  (loaiDonViId == null ? "" :
                                                   "&loaidonviid=" +
                                                   loaiDonViId) +
                                                  (langCode == null ? "" :
                                                   "&langcode=" + langCode));
                            listTieuDe.add(goLink);
                        }

                    }
                }
            }
            RichOutputText outputText = new RichOutputText();
            outputText.setValue(" (");
            listNgayThang.add(outputText);
            Object obj =
                cbttView1Iterator.getCurrentRow().getAttribute("NgayTao");
            if (obj != null) {
                oracle.jbo.domain.Date valDate = (oracle.jbo.domain.Date)obj;
                if (valDate != null) {
                    java.util.Date date = valDate.dateValue();
                    if (date != null) {
                        outputText = new RichOutputText();
                        outputText.setValue(date);
                        DateTimeConverter converter =
                            (DateTimeConverter)FacesContext.getCurrentInstance().getApplication().createConverter("javax.faces.DateTime");
                        converter.setLocale(new Locale(langCode));
                        converter.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
                        converter.setType("date");
                        converter.setDateStyle("short");
                        outputText.setConverter(converter);
                        listNgayThang.add(outputText);
                    }
                }
            }

            outputText = new RichOutputText();
            outputText.setValue(")");
            listNgayThang.add(outputText);
            RichPanelBorderLayout borderLayout = new RichPanelBorderLayout();
            borderLayout.setStyleClass("cbtt-title");
            RichPanelGroupLayout groupLayout = new RichPanelGroupLayout();
            groupLayout.setStyleClass("cbtt-des");
            groupLayout.setLayout(groupLayout.LAYOUT_VERTICAL);


            String donvi = (String)mapValue.get("donvi");
            if (donvi != null) {
                outputText = new RichOutputText();
                outputText.setInlineStyle("font-weight:bold");
                outputText.setValue(donvi);
                borderLayout.getChildren().add(outputText);
            }
            borderLayout.getChildren().addAll(listNgayThang);
            groupLayout.getChildren().addAll(listTieuDe);
            danhSachPanel.getChildren().add(borderLayout);
            danhSachPanel.getChildren().add(groupLayout);
        }
        AdfFacesContext.getCurrentInstance().addPartialTarget(danhSachPanel);
    }

    private void resetPaging(String iteratorName, int pageNum) {
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        FacesContext fc = FacesContext.getCurrentInstance();
        Application app = fc.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = fc.getELContext();
        pagingPanel.getChildren().clear();
        DCIteratorBinding iterator = Utils.getIteratorBinding(iteratorName);
        int rowCount = (int)iterator.getEstimatedRowCount();
        int pageSize =
            DEFAULT_SIZE; //Utils.getPageSize("HtCauHinhView1Iterator");
        try {
            pageSize =
                    Integer.parseInt((String)request.getPortletSession().getAttribute("soluongbanghi"));
        } catch (Exception e) {

        }
        int pageCount = 1;
        if (rowCount > pageSize) {
            if (rowCount % pageSize == 0) {
                pageCount = rowCount / pageSize;
            } else {
                pageCount = rowCount / pageSize + 1;
            }
        }

        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageNum > pageCount) {
            pageNum = pageCount;
        }
        int first = 1;
        if (pageNum < 3) {
            first = 1;
        } else if (pageNum + 5 > pageCount) {
            if (pageNum + 2 > pageCount) {
                if (pageCount - 4 < 1)
                    first = 1;
                else {
                    first = pageCount - 4;
                }
            } else {
                if (pageCount < 6) {
                    first = 1;
                } else {
                    first = pageNum - 2;
                }
            }
        } else {
            first = pageNum - 2;
        }

        MethodExpression methodExpression =
            elFactory.createMethodExpression(elContext, "#{dscbtt.changePage}",
                                             null,
                                             new Class[] { ActionEvent.class });
        MethodExpressionMethodBinding methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
        RichCommandLink commandLink = new RichCommandLink();
        commandLink.setPartialSubmit(true);
        commandLink.setText(getResource("PREV"));
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("pageNum", pageNum - 1);
        commandLink.setInlineStyle("display:block;width:60px;text-align:center;padding-right:3px;");
        pagingPanel.getChildren().add(commandLink);
        if (pageNum == 1) {
            commandLink.setDisabled(true);
        } else {
            commandLink.setDisabled(false);
        }
        if(pageNum>3){
        methodExpression =
            elFactory.createMethodExpression(elContext, "#{dscbtt.changePage}",
                                             null,
                                             new Class[] { ActionEvent.class });
        methodExpressionMethodBinding =
            new MethodExpressionMethodBinding(methodExpression);
            RichCommandLink commandLinkFirst = new RichCommandLink();
            commandLinkFirst.setPartialSubmit(true);
            commandLinkFirst.setText("" +1);
            commandLinkFirst.getAttributes().put("actionListener",
                                            methodExpressionMethodBinding);
            commandLinkFirst.getAttributes().put("pageNum", 1);
            commandLinkFirst.setInlineStyle("display:block;padding-right:3px;font-weight:bold;");
            pagingPanel.getChildren().add(commandLinkFirst);
            RichOutputText outputText=new RichOutputText();
            outputText.setValue("...");
            pagingPanel.getChildren().add(outputText);
        }
        for (int i = first, j = 0; i <= pageCount && j < 5; i++, j++) {
            methodExpression =
                    elFactory.createMethodExpression(elContext, "#{dscbtt.changePage}",
                                                     null,
                                                     new Class[] { ActionEvent.class });
            methodExpressionMethodBinding =
                    new MethodExpressionMethodBinding(methodExpression);
            commandLink = new RichCommandLink();
            commandLink.setPartialSubmit(true);
            if (i == pageNum) {
                commandLink.setDisabled(true);
                commandLink.setInlineStyle("display:block;padding-right:3px;font-weight:bold; color:#CCC;");
            } else {
                commandLink.setInlineStyle("display:block;padding-right:3px;font-weight:bold;");
            }
            if(i==pageCount){
            commandLink.setText("" + i+"["+rowCount+"]");
            }else{
                commandLink.setText("" + i);
            }
            commandLink.getAttributes().put("actionListener",
                                            methodExpressionMethodBinding);
            commandLink.getAttributes().put("pageNum", i);
            pagingPanel.getChildren().add(commandLink);
        }
        if (pageNum+2 < pageCount) {
        methodExpression =
                elFactory.createMethodExpression(elContext, "#{dscbtt.changePage}",
                                                 null,
                                                 new Class[] { ActionEvent.class });
        methodExpressionMethodBinding =
                new MethodExpressionMethodBinding(methodExpression);
            RichOutputText outputText=new RichOutputText();
            outputText.setValue("...");
        pagingPanel.getChildren().add(outputText);
            
            RichCommandLink commandLinkLast = new RichCommandLink();
            commandLinkLast.setPartialSubmit(true);
            commandLinkLast.setText("" + pageCount+"["+rowCount+"]");
            commandLinkLast.getAttributes().put("actionListener",
                                            methodExpressionMethodBinding);
            commandLinkLast.getAttributes().put("pageNum", pageCount);
                commandLink.setInlineStyle("display:block;padding-right:3px;font-weight:bold;");
        pagingPanel.getChildren().add(commandLinkLast);
        }
        methodExpression =
                elFactory.createMethodExpression(elContext, "#{dscbtt.changePage}",
                                                 null,
                                                 new Class[] { ActionEvent.class });
        methodExpressionMethodBinding =
                new MethodExpressionMethodBinding(methodExpression);
        commandLink = new RichCommandLink();
        commandLink.setPartialSubmit(true);
        commandLink.setText(getResource("NEXT"));
        commandLink.getAttributes().put("actionListener",
                                        methodExpressionMethodBinding);
        commandLink.getAttributes().put("pageNum", pageNum + 1);
        commandLink.setInlineStyle("display:block;width:60px;text-align:center;padding-right:3px;");
        pagingPanel.getChildren().add(commandLink);
        if (pageNum == pageCount) {
            commandLink.setDisabled(true);
        } else {
            commandLink.setDisabled(false);
        }

        iterator.executeQuery();
        if ((pageNum) * pageSize > rowCount) {
            iterator.setRangeSize(rowCount - (pageNum - 1) * pageSize);
        } else {
            iterator.setRangeSize(pageSize);
        }
        iterator.setRangeStart((pageNum - 1) * pageSize);

        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanel);
    }

    private void resetIterator(PortletRequest request) {
        String loaiCbttId =
            (String)request.getPortletSession().getAttribute("loaicbttid");
        String loaiDonViId =
            (String)request.getPortletSession().getAttribute("loaidonviid");
        String langCode =
            (String)request.getPortletSession().getAttribute("langcode");
        if (langCode == null) {
            langCode = DEFAULT_LANGCODE;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String fromSearch =
            (String)request.getPortletSession().getAttribute(SEARCH_TU_NGAY);
        String toSearch =
            (String)request.getPortletSession().getAttribute(SEARCH_DEN_NGAY);
        java.util.Date tuNgay = null;
        java.util.Date denNgay = null;
        if (fromSearch != null) {
            try {
                tuNgay = dateFormat.parse(fromSearch);
            } catch (ParseException e) {
            }
        }
        if (toSearch != null) {
            try {
                denNgay = dateFormat.parse(toSearch);
            } catch (ParseException e) {
            }
        }

        List<AdvancedSearchGroup> listASG = new ArrayList();
        AdvancedSearchGroup asgTrangThai = new AdvancedSearchGroup();
        listASG.add(asgTrangThai);
        AdvancedSearchItem asiTrangThai = new AdvancedSearchItem();
        asgTrangThai.getListChildren().add(asiTrangThai);
        asiTrangThai.setItemName("TrangThai");
        asiTrangThai.setRequired(true);
        asiTrangThai.getListValue().add(0,
                                        new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        if (loaiCbttId != null) {
            try {
                Number loaiCbttNumber = new Number(loaiCbttId);
                AdvancedSearchGroup asg = new AdvancedSearchGroup();
                listASG.add(asg);
                AdvancedSearchItem asiLoaiCbtt = new AdvancedSearchItem();
                asg.getListChildren().add(asiLoaiCbtt);
                asiLoaiCbtt.setItemName("DlctLoaiCbtt");
                asiLoaiCbtt.getListValue().add(loaiCbttNumber);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (tuNgay != null) {
            AdvancedSearchGroup asg = new AdvancedSearchGroup();
            listASG.add(asg);
            AdvancedSearchItem asi = new AdvancedSearchItem();
            asg.getListChildren().add(asi);
            asi.setItemName("NgayTao");
            asi.setOperator(AdvancedSearchItem.OPER_ON_OR_AFTER);
            asi.getListValue().add(new oracle.jbo.domain.Date(new Timestamp(tuNgay.getTime())));
        }
        if (denNgay != null) {
            AdvancedSearchGroup asg = new AdvancedSearchGroup();
            listASG.add(asg);
            AdvancedSearchItem asi = new AdvancedSearchItem();
            asg.getListChildren().add(asi);
            asi.setItemName("NgayTao");
            asi.setOperator(AdvancedSearchItem.OPER_ON_OR_BEFORE);
            asi.getListValue().add(new oracle.jbo.domain.Date(new Timestamp(denNgay.getTime())));
        }
        {
            try {
                AdvancedSearchGroup asg = new AdvancedSearchGroup();
                listASG.add(asg);
                AdvancedSearchItem asi = new AdvancedSearchItem();
                asg.getListChildren().add(asi);
                asi.setItemName("DlctDonViLoaiDonViView");
                asi.setRequired(true);
                asi.setOperator(AdvancedSearchItem.OPER_EXISTS);
                if (loaiDonViId != null) {
                    Number loaiDonViNumber = new Number(loaiDonViId);
                    AdvancedSearchGroup asgChild = new AdvancedSearchGroup();
                    asi.getListChildren().add(asgChild);
                    AdvancedSearchItem asiChild = new AdvancedSearchItem();
                    asgChild.getListChildren().add(asiChild);
                    asiChild.setItemName("DlctLoaiDonViId");
                    asiChild.setRequired(true);
                    asiChild.getListValue().add(loaiDonViNumber);
                }
                AdvancedSearchGroup asgChild = new AdvancedSearchGroup();
                asi.getListChildren().add(asgChild);
                AdvancedSearchItem asiChild = new AdvancedSearchItem();
                asgChild.getListChildren().add(asiChild);
                asiChild.setItemName("TrangThai");
                asiChild.setRequired(true);
                asiChild.getListValue().add(new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
            } catch (Exception e) {
            }
        }
        if (langCode != null) {
            try {
                AdvancedSearchGroup asg = new AdvancedSearchGroup();
                listASG.add(asg);
                AdvancedSearchItem asi = new AdvancedSearchItem();
                asg.getListChildren().add(asi);
                asi.setItemName("DlctCbttNnView");
                asi.setRequired(true);
                asi.setOperator(AdvancedSearchItem.OPER_EXISTS);
                AdvancedSearchGroup asgChild = new AdvancedSearchGroup();
                asi.getListChildren().add(asgChild);
                AdvancedSearchItem asiChild = new AdvancedSearchItem();
                asgChild.getListChildren().add(asiChild);
                asiChild.setItemName("DlctNgonNguView");
                asiChild.setRequired(true);
                asiChild.setOperator(AdvancedSearchItem.OPER_EXISTS);
                AdvancedSearchGroup asgChild2 = new AdvancedSearchGroup();
                asiChild.getListChildren().add(asgChild2);
                AdvancedSearchItem asiChild2 = new AdvancedSearchItem();
                asgChild2.getListChildren().add(asiChild2);
                asiChild2.setItemName("Ma");
                asiChild2.setRequired(true);
                asiChild2.getListValue().add(langCode);
            } catch (Exception e) {
            }
        }
        Utils.searchadvanced("DlctCbttView1Iterator", listASG);

        listASG = new ArrayList();
        asgTrangThai = new AdvancedSearchGroup();
        listASG.add(asgTrangThai);
        asiTrangThai = new AdvancedSearchItem();
        asgTrangThai.getListChildren().add(asiTrangThai);
        asiTrangThai.setItemName("TrangThai");
        asiTrangThai.setRequired(true);
        asiTrangThai.getListValue().add(0,
                                        new Number(Utils.ENUM_TRANG_THAI.CONG_BO.getId()));
        AdvancedSearchGroup asgLoaiTruongTt = new AdvancedSearchGroup();
        listASG.add(asgLoaiTruongTt);
        AdvancedSearchItem asiLoaiTruongTt = new AdvancedSearchItem();
        asgLoaiTruongTt.getListChildren().add(asiLoaiTruongTt);
        asiLoaiTruongTt.setItemName("DlctLoaiTruongTt");
        asiLoaiTruongTt.setRequired(true);
        asiLoaiTruongTt.getListValue().add(0,
                                           new Number(Utils.ENUM_LOAI_TRUONG_TT.CONG_BO_THONG_TIN.getId()));
        if (langCode != null) {
            try {
                AdvancedSearchGroup asg = new AdvancedSearchGroup();
                listASG.add(asg);
                AdvancedSearchItem asi = new AdvancedSearchItem();
                asg.getListChildren().add(asi);
                asi.setItemName("DlctNgonNguView");
                asi.setRequired(true);
                asi.setOperator(AdvancedSearchItem.OPER_EXISTS);
                AdvancedSearchGroup asgChild = new AdvancedSearchGroup();
                asi.getListChildren().add(asgChild);
                AdvancedSearchItem asiChild = new AdvancedSearchItem();
                asgChild.getListChildren().add(asiChild);
                asiChild.setItemName("Ma");
                asiChild.setRequired(true);
                asiChild.getListValue().add(langCode);
            } catch (Exception e) {
            }
        }
        Utils.searchadvanced("DlctTruongTtView1Iterator", listASG);
    }


    public void timKiem(ActionEvent actionEvent) {
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        RichInputDate inputFrom = null;
        RichInputDate inputTo = null;
        List<UIComponent> listChild = searchPanel.getChildren();
        for (UIComponent uiComponent : listChild) {
            if (uiComponent != null && uiComponent instanceof RichInputDate) {
                if (SEARCH_TU_NGAY.equals(uiComponent.getId())) {
                    inputFrom = (RichInputDate)uiComponent;
                } else if (SEARCH_DEN_NGAY.equals(uiComponent.getId())) {
                    inputTo = (RichInputDate)uiComponent;
                }
            }
        }
        if (inputFrom != null && inputFrom.getValue() != null) {
            if (inputTo != null && inputTo.getValue() != null) {
                java.util.Date from = (java.util.Date)inputFrom.getValue();
                java.util.Date to = (java.util.Date)inputTo.getValue();
                request.getPortletSession().setAttribute(SEARCH_TU_NGAY,
                                                         dateFormat.format(from));
                request.getPortletSession().setAttribute(SEARCH_DEN_NGAY,
                                                         dateFormat.format(to));
            } else {
                request.getPortletSession().setAttribute(SEARCH_TU_NGAY,
                                                         dateFormat.format((java.util.Date)inputFrom.getValue()));
                request.getPortletSession().setAttribute(SEARCH_DEN_NGAY,
                                                         null);

            }
        } else if (inputTo != null && inputTo.getValue() != null) {
            request.getPortletSession().setAttribute(SEARCH_TU_NGAY, null);
            request.getPortletSession().setAttribute(SEARCH_DEN_NGAY,
                                                     dateFormat.format((java.util.Date)inputTo.getValue()));
        }else{
            request.getPortletSession().setAttribute(SEARCH_TU_NGAY, null);
            request.getPortletSession().setAttribute(SEARCH_DEN_NGAY,null);
        }
        request.getPortletSession().setAttribute("resettabbed", 0);
        resetIterator(request);
        createForm(0);
        AdfFacesContext.getCurrentInstance().addPartialTarget(danhSachPanel);
        AdfFacesContext.getCurrentInstance().addPartialTarget(pagingPanel);
    }
    
    private String getResource(String resourceKey) {
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String langCode =
            (String)request.getPortletSession().getAttribute("langcode");
        if (langCode == null) {
            langCode = DEFAULT_LANGCODE;
        }
        Locale locale = new Locale(langCode);
        ResourceBundle bundle =
            ResourceBundle.getBundle("portlet.dscbtt.resource.DscbttBundle",
                                     locale);
        return bundle.getString(resourceKey);
    }

    public String getTieuDe() {
        PortletRequest request =
            (PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        return request.getParameter("tieude");
    }

    public void setDanhSachPanel(RichPanelGroupLayout danhSachPanel) {
        this.danhSachPanel = danhSachPanel;
    }

    public RichPanelGroupLayout getDanhSachPanel() {
        return danhSachPanel;
    }

    public void setPagingPanel(RichPanelGroupLayout pagingPanel) {
        this.pagingPanel = pagingPanel;
    }

    public RichPanelGroupLayout getPagingPanel() {
        return pagingPanel;
    }

    public void setSearchPanel(RichPanelGroupLayout searchPanel) {
        this.searchPanel = searchPanel;
    }

    public RichPanelGroupLayout getSearchPanel() {
        return searchPanel;
    }
}
